package com.wjh.www.service.impl;

import com.wjh.www.annotation.spring.Autowired;
import com.wjh.www.annotation.spring.Component;
import com.wjh.www.controller.util.DoFilterUtil;
import com.wjh.www.dao.mapper.*;
import com.wjh.www.entity.bo.TokenBo;
import com.wjh.www.entity.bo.UserLoginBo;
import com.wjh.www.entity.dto.CommonResult;
import com.wjh.www.entity.po.*;
import com.wjh.www.entity.vo.UserInfoVo;
import com.wjh.www.service.UserService;
import com.wjh.www.service.constant.RoleConstant;
import com.wjh.www.service.constant.SystemConstant;
import com.wjh.www.util.SecurityUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户相关业务
 *
 * @author wjh
 * @date 2021/9/9 17:23
 * @Package com.wjh.anyview.service.impl
 */
@Component
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public CommonResult<String> login(UserLoginBo userLoginBo) {
        User userSelect = new User();
        userSelect.setNum(userLoginBo.getNum());
        userSelect.setPassword(SecurityUtil.encrypt(userLoginBo.getPassword()));
        User user = userMapper.selectOneByFields(userSelect);
        System.out.println(user);
        if (user != null) {
            //查询用户的权限
            List<Permission> permissions = permissionMapper.listPermissionsByUserId(user.getId());
            List<String> permissionList = new ArrayList<>();
            for (Permission permission : permissions) {
                permissionList.add(permission.getPermission());
            }
            //查询用户的角色
            List<Role> roles = roleMapper.listRoleByUserId(user.getId());
            List<String> roleList = new ArrayList<>();
            for (Role role : roles) {
                roleList.add(role.getRole());
            }

            //如果该用户具有该角色则可以登录
            if (roleList.contains(userLoginBo.getLoginPosition())) {
                TokenBo tokenBo = new TokenBo();
                tokenBo.setId(user.getId());
                tokenBo.setPermissionList(permissionList);
                tokenBo.setRoleList(roleList);
                tokenBo.setExpireAt(DoFilterUtil.DURATION_TIME + System.currentTimeMillis());
                //密码置为null
                user.setPassword(null);
                tokenBo.setUser(user);
                //登录成功返回token
                return CommonResult.operateSuccess(SecurityUtil.getToken(tokenBo));
            }
            //该用户没有他所选的登录的角色
            return CommonResult.operateFailWithMessage("您的账号不能登录该角色!");
        }
        return CommonResult.operateFailWithMessage("登录失败，账号或密码错误!");
    }

    @Override
    public CommonResult<?> register(User user) {
        User userSelect = new User();
        userSelect.setNum(user.getNum());
        User result = userMapper.selectOneByFields(userSelect);
        if (result != null) {
            return CommonResult.operateFailWithMessage("该学号已经注册过了");
        }
        userMapper.insert(user);

        //分配身份
        User u = userMapper.selectOneByFields(userSelect);
        UserRole userRole1 = new UserRole();
        userRole1.setRoleId(RoleConstant.STUDENT_ID);
        userRole1.setUserId(u.getId());
        UserRole userRole2 = new UserRole();
        userRole2.setRoleId(RoleConstant.USER_ID);
        userRole2.setUserId(u.getId());
        userRoleMapper.insert(userRole1);
        userRoleMapper.insert(userRole2);
        return CommonResult.operateSuccess();
    }

    @Override
    public CommonResult<?> saveUser(User user) {
        //根据num来判断该user是否已经注册过了
        User fields = new User();
        fields.setNum(user.getNum());
        if (userMapper.selectOneByFields(fields) != null) {
            return CommonResult.operateFailWithMessage("该用户已经存在本系统，无法再次注册!");
        }

        if (userMapper.insert(user) > 0) {
            return CommonResult.operateSuccess();
        }
        return CommonResult.operateFailWithMessage(SystemConstant.SYSTEM_ERROR);
    }

    @Override
    public void setRole(Long userId, String role) {
        //获取被设置的角色的id
        Role roleSelect = new Role();
        roleSelect.setRole(role);
        Role resultRole = roleMapper.selectOneByFields(roleSelect);

        //把该用户设置为该角色
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(resultRole.getId());
        userRoleMapper.insert(userRole);
    }

    @Override
    public CommonResult<?> saveStudent(User user) {
        if (!saveUser(user).isSuccess()) {
            return CommonResult.operateFailWithMessage("该学生已经存在本系统，无法添加!");
        }
        User resultUser = userMapper.selectOneByFields(user);
        setRole(resultUser.getId(), RoleConstant.STUDENT);
        return CommonResult.operateSuccess();
    }

    @Override
    public CommonResult<?> saveAdmin(User user) {
        if (!saveUser(user).isSuccess()) {
            return CommonResult.operateFailWithMessage("该管理员已经存在本系统，无法添加!");
        }
        User resultUser = userMapper.selectOneByFields(user);
        setRole(resultUser.getId(), RoleConstant.ADMIN);
        return CommonResult.operateSuccess();
    }

    @Override
    public CommonResult<UserInfoVo> selectUserByNum(String num) {
        //根据num来查询user
        User userSelect = new User();
        userSelect.setNum(num);
        User user = userMapper.selectOneByFields(userSelect);
        if (user == null) {
            return CommonResult.operateFailWithMessage("您输入的学工号不正确");
        }
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setClassName("没有班级");
        if (user.getClassId() != 0) {
            Clazz clazz = clazzMapper.selectById(new Clazz(user.getClassId()));
            userInfoVo.setClassName(clazz.getName());
        }
        userInfoVo.setId(user.getId());
        userInfoVo.setNum(user.getNum());
        userInfoVo.setGrade(user.getGrade());
        userInfoVo.setSex(user.getSex());
        userInfoVo.setName(user.getName());
        userInfoVo.setTelephone(user.getTelephone());
        return CommonResult.operateSuccess(userInfoVo);
    }

    @Override
    public CommonResult<?> updateUserById(User user) {
        //id不可以为null，学工号num不可以修改
        if (user.getId() == null || user.getNum() != null) {
            return CommonResult.operateFailWithMessage("信息不符合要求，修改失败");
        }
        if (userMapper.updateById(user) > 0) {
            return CommonResult.operateSuccess();
        }
        return CommonResult.operateFailWithMessage(SystemConstant.SYSTEM_ERROR);
    }

    @Override
    public CommonResult<?> deleteUserById(Long userId) {
        //根据uid来删除用户
        User userDelete = new User();
        userDelete.setId(userId);
        if (userMapper.delete(userDelete) > 0) {
            return CommonResult.operateSuccess();
        }
        return CommonResult.operateFailWithMessage(SystemConstant.SYSTEM_ERROR);
    }

    @Override
    public CommonResult<User> getUserByToken(String tokenString) {
        TokenBo tokenBo = SecurityUtil.decodeToken(tokenString);
        System.out.println(tokenBo);
        return CommonResult.operateSuccess(tokenBo.getUser());
    }

}
